package cn.dao789.mvp;

import cn.dao789.model.UserModel;

/**
 * MVP架构中的Presenter
 * 连接View和Model，处理业务逻辑，并通过View接口更新UI
 */
public class UserPresenter {
    private UserView userView;
    private UserModel userModel;
    
    public UserPresenter(UserView userView) {
        this.userView = userView;
        // 初始化Model
        this.userModel = new UserModel("2", "MVP用户", "mvp@example.com");
    }
    
    // 初始化View，显示用户信息
    public void initView() {
        if (userView != null) {
            userView.showUserInfo(userModel.getUserId(), 
                                 userModel.getUsername(), 
                                 userModel.getEmail());
        }
    }
    
    // 处理保存用户的业务逻辑
    public void saveUser() {
        if (userView != null) {
            String username = userView.getUsernameInput();
            String email = userView.getEmailInput();
            
            // 验证输入
            if (username == null || username.isEmpty()) {
                username = "未命名用户";
            }
            
            if (email == null || email.isEmpty()) {
                email = "noemail@example.com";
            }
            
            // 更新Model
            userModel.setUsername(username);
            userModel.setEmail(email);
            
            // 通过View接口更新UI
            userView.showUserInfo(userModel.getUserId(), username, email);
            userView.showSaveSuccessMessage();
        }
    }
    
    // 释放View引用，避免内存泄漏
    public void onDestroy() {
        this.userView = null;
    }
}